/**
 * 上传组件
 * add by lifenping
 * on 20200301
 */
import React, { Component } from 'react';
import { Modal, Form, Input, Icon, Upload, Button } from 'antd';

const FormItem = Form.Item;

interface PropsType {
  form?: any;
  name: string;
  action?: any;
  data?: any;
  label: string;
  rules?: [];
  listType?: any;
  initialValue?:any;
}

interface stateType {
  previewVisible?: boolean;
  previewImage?: any;
  fileList?: [];
  // 已有列表
  newInit?:[];
}

export default class UploadItem extends Component<PropsType, stateType> {
  constructor(props: PropsType) {
    super(props);

    const {initialValue} = props;
    // 处理initialValue格式
    const newInit = initialValue
      ? [
          {
            uid: '-1',
            name: initialValue.split('/').pop(),
            status: 'done',
            url: initialValue,
          },
        ]
      : [];

    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      newInit,
    };
  }


  getBase64 = file =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });

  onChange = params => {
    const { form, name } = this.props;
    const rs = params.file.response;
    if (rs && JSON.stringify(rs) !== '{}') {
      form.setFieldsValue({
        [name]: rs.data,
      });
    }
    this.setState({
      fileList: params.fileList,
    });
  };

  handleCancel = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({ previewVisible: false, fileList: [] });
  };

  onPreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  onRemove=()=>{
    this.setState({
      fileList:[],
      newInit:[],
    })
  }

  render() {
    const { label, name, initialValue, rules, form, ...others } = this.props;
    const { previewImage, previewVisible, fileList, newInit } = this.state;

    return (
      <FormItem label={label} hasFeedback={!!rules}>
        {form.getFieldDecorator(name, {
          // initialValue:newInit,
          rules,
        })(
          <div>
            <Upload
              defaultFileList={newInit}
              onChange={this.onChange}
              onPreview={this.onPreview}
              onRemove={this.onRemove}
              {...others}
            >
              {fileList.length < 1 && newInit.length < 1 ? (
                <Button>
                  <Icon type="upload" />
                  上传
                </Button>
              ) : null}
            </Upload>

            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </div>,
        )}
      </FormItem>
    );
  }
}
